package chain

import (
	"awesomeProject1/pkg/chain/ethclient"
	"context"
	"fmt"
	"github.com/simplechain-org/client/rpc"
	"math/big"
	"time"
)

type Client struct {
	rpcClient *rpc.Client
	client    *ethclient.Client
	config    *Config
}

func NewClient(config *Config) (*Client, error) {
	//todo 校验protocol port
	var rpcClient *rpc.Client
	var err error
	if config.TLSEnable {
		nodeURL := fmt.Sprintf("%ss://%s:%d", config.Protocol, config.Domain, config.Port)
		rpcClient, err = rpc.DialWithTLS(nodeURL, config.CertFile, config.KeyFile, config.RootCertFiles)
		if err != nil {
			return nil, err
		}
	} else {
		nodeURL := fmt.Sprintf("%s://%s:%d", config.Protocol, config.Domain, config.Port)
		rpcClient, err = rpc.Dial(nodeURL)
		if err != nil {
			return nil, err
		}
	}
	return &Client{
		rpcClient: rpcClient,
		client:    ethclient.NewClient(rpcClient),
		config:    config,
	}, nil
}
func (c *Client) ChainId() (*big.Int, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*15)
	defer cancel()
	return c.client.ChainID(ctx)
}
func (c *Client) GetEthClient() *ethclient.Client {
	return c.client
}
